//
//  EpointAttachDownloadListViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 14-4-3.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointAttachDownloadListViewController.h"
#import "EpointAttachDownListTableViewCell.h"
#import "EpointFileOpenViewController.h"
#import "SGdownloader.h"
#import "UIImage+Tint.h"

@interface EpointAttachDownloadListViewController ()
{
    UITableView *tv;
    NSMutableArray *fileList;
    NSArray *sfixs;
    SGdownloader* sgdownload;
    BOOL isTodoAttach;
}
@end

@implementation EpointAttachDownloadListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitle:@"附件"];
    
    sfixs = [NSArray arrayWithObjects:@".doc",@".docx",@".xls",@".xlsx",@"ppt",@".pptx",@".pdf",@".pot",@".png",@".jpg",@".jpeg",@"gif",@".txt",@".sql",@".bmp",@".xml",@".html",@".mp4", nil];
    fileList = [self.passParam objectForKey:@"FileList"];
    isTodoAttach =[[self.passParam objectForKey:@"isTodoAttach"] boolValue];
    tv = [[UITableView alloc]initWithFrame:[self getFullContentFrame]];
    tv.dataSource = self;
    tv.delegate = self;
    
    [self.view addSubview:tv];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (CurrentDeviceISiPad) {
        return 66;
    }
    return 43;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"EpointAttachDownListTableViewCell";
    EpointAttachDownListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        if (cell==nil) {
            NSString *nibName = @"EpointAttachDownListTableViewCell";
            if (CurrentDeviceISiPad) {
                nibName = @"EpointAttachDownListTableViewCell_pad";
            }
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:nibName owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
    }
    NSMutableDictionary *dic = [fileList objectAtIndex:indexPath.row];
    NSString *fileName = [dic objectForKey:@"FileName"];
    cell.fileNameLabel.text = fileName;
    [cell.iconView setImage:[UIImage imageNamed:[EpointAttachDownloadListViewController getImageNameByFileName:fileName]]];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return fileList.count;
}

+(NSString *)getImageNameByFileName:(NSString *)fileName
{
    fileName = [fileName lowercaseString];
    NSArray *arr = [fileName componentsSeparatedByString:@"."];
    NSString *sufStr = [arr objectAtIndex:arr.count-1];
    NSString *imageName = [NSString stringWithFormat:@"ico_%@_large",sufStr];
    NSData *imagedata=UIImagePNGRepresentation([UIImage imageNamed:imageName]);
    if (imagedata.length==0) {
        imageName = @"ico_document_large";
    }
    return imageName;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dic = [fileList objectAtIndex:indexPath.row];
    NSString *fileName = [dic objectForKey:@"FileName"];
    int aflag = 0;
    for (NSString *s in sfixs) {
        if ([EpointStringUtil endWith:s forString:[fileName lowercaseString]]) {
            aflag = 1;
            break;
        }
    }
    
    if (aflag==0) {
        [self toastMessage:@"不支持该文件格式打开！"];
    }
    else
    {
        if ([[dic objectForKey:@"isBigFile"]isEqualToString:@"1"]) {
            [self toastMessage:@"大附件无法加载！"];
        }
        else{
            
            NSString* dirPath = [NSString stringWithFormat:@"%@/Documents/attaches/%@/",NSHomeDirectory(),[self.passParam objectForKey:@"FolderGuid"]];
            
            NSString* filePath = [NSString stringWithFormat:@"%@%@",dirPath,[dic objectForKey:@"FileName"]];
            
            NSError *error;
            NSDictionary* dictFile = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
            long nFileSize = [dictFile fileSize];
            if (([[NSFileManager defaultManager] fileExistsAtPath:filePath]&&nFileSize>0)&&!isTodoAttach) {
                [self loadSysOpen:filePath];
            }
            else
            {
                [self showMBPHUDWithMessage:@"正在加载文件..."];
                NSString *url = [dic objectForKey:@"FileUrl"];
                sgdownload = [[SGdownloader alloc]initWithURL:[NSURL URLWithString:url] timeout:20];
                [sgdownload startWithDownloading:^(float progressValue,NSInteger percentage){
                
                } onFinished:^(NSData *fileData)
                {
                    [self hideMBPHUD];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
                    [fileManager createFileAtPath:filePath contents:fileData attributes:nil];
                    if (fileData.length==0) {
                        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                        [self toastMessage:@"附件加载失败！"];
                    }
                    else
                    {
                        [self loadSysOpen:filePath];
                    }
                } onFail:^(NSError *error){
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                    [self toastMessage:@"附件加载失败！"];
                }];
            }
        }
    }
}

-(void)loadSysOpen:(NSString *)path
{
    self.documentController =
    [UIDocumentInteractionController
     interactionControllerWithURL:[NSURL fileURLWithPath:path]];
    self.documentController.delegate = self;
    [self.documentController presentPreviewAnimated:YES];
}

-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

-(void)loadFile:(NSString *)path
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    EpointFileOpenViewController *v = [[EpointFileOpenViewController alloc]init];
    [params setObject:path forKey:@"FilePath"];
    v.passParam = params;
    [self.navigationController pushViewController:v animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
